package com.yimi.yinhepda.views.break_card;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.ym.utils.SysInfo;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.request.G7BreakCardRequest;
import com.yimi.yinhepda.entity.response.BreakCardResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.updateApk.UpdateApk;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.ExitDialog;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;

/**
 * G7打卡界面
 *
 * @author 000432
 * @date 2018/5/26 0026
 */

public class BreadCardActivity extends BaseActivity {
    /**
     * 返回按钮
     */
    private ImageButton ibBack;
    private boolean isRunning = false;

    @Override
    public String getPageName() {
        return "G7打卡界面";
    }

    public BreadCardActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_break_card);

        //初始化系统信息类
        SysInfo.getInstance().init(this);
        sharedPreferUtil.setBooleanValue(Common.PDT_DEV, true);

        ibBack = (ImageButton) findViewById(R.id.ib_back);
        ibBack.setOnClickListener(this);

        //启用扫描头
        enableScanHead(true);
        //将连续扫描打开
        scanContinue(true);
        //关闭声音
        soundPlay(false);

        //设置常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //校验设备型号
        String phoneModel = SysInfo.getInstance().getPhoneModel();
        if (phoneModel != null) {
            if (phoneModel.equals(Common.DEV_MODEL)) {
                //横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            }
        }
    }

    @Override
    public void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            LogUtil.e("result=" + result);
            doScan(result);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ib_back:
                showExitDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            showExitDialog();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 执行扫描结果
     *
     * @param result 扫描结果
     */
    private void doScan(String result) {
        if (isRunning) {
            return;
        }

        //检测更新版本
        UpdateApk.getInstance(this, sharedPreferUtil).upgrade();

        isRunning = true;
        showPgDlg("打卡中...");

        //去除回车符
        result = StringUtils.replaceBlank(result);

        G7BreakCardRequest breakCardRequest = new G7BreakCardRequest();
        breakCardRequest.setTaskNo(result);
        breakCardRequest.setDeptCode(sharedPreferUtil.getDeptCode());
        breakCardRequest.setCompCode(sharedPreferUtil.getCompanyCode());
        breakCardRequest.setPuncherCode(sharedPreferUtil.getValue(Common.USER_CODE));
        breakCardRequest.setPuncherName(sharedPreferUtil.getEmpName());

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setUrl(Constants.URL_CAR_CLOCK_FOR_MACHINE)
                .setRequestObject(breakCardRequest)
                .setResponsClazz(BreakCardResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        isRunning = false;
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        isRunning = false;
                        dismissPgDlg();
                        if (obj instanceof BreakCardResponse) {
                            BreakCardResponse response = (BreakCardResponse) obj;
                            String data = response.getData();
                            breakCardDialog(data);
                        }
                    }
                });
    }

    /**
     * 打卡结果提示框
     */
    private void breakCardDialog(String data) {
        LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_break_card, null);
        TextView tvBreakResult = layout.findViewById(R.id.tv_breakRsult);
        final Dialog breakDialog = new Dialog(this, R.style.AsyncTaskDialog);
        breakDialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        breakDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        breakDialog.getWindow().getDecorView().setPadding(30, 0, 30, 0);
        breakDialog.setCanceledOnTouchOutside(false);
        WindowManager.LayoutParams layoutParams = breakDialog.getWindow().getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        breakDialog.getWindow().setAttributes(layoutParams);
        breakDialog.show();
        tvBreakResult.setText("打卡成功!");
        if (data.equals("重复打卡")) {
            tvBreakResult.setText(data);
        }

        SoundVibratorManager.playSound(1);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                breakDialog.dismiss();
            }
        }, 3 * 1000 + 500);
    }

    /**
     * 退出密码对话框
     */
    protected void showExitDialog() {
        final ExitDialog exitDialog = new ExitDialog(this);
        exitDialog.setPositiveClickListener(R.drawable.btn_confirm_selector, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String pwd = exitDialog.getmExitPwd().getText().toString().trim();
                if (pwd.equals("753159")) {
                    //跳转至系统设置界面
                    toActivity(BreakCardSettingActivity.class);
                    dialog.dismiss();
                } else if (pwd.equals("")) {
                    showToast("请输入退出密码！");
                } else {
                    showToast("退出密码不正确！");
                }
            }
        });
        exitDialog.setCanceledOnTouchOutside(false);
        exitDialog.setCancelable(false);
        exitDialog.show();
    }

    /**
     * 启用/禁用扫描头
     *
     * @param flag 是否开启标志
     */
    public void enableScanHead(boolean flag) {
        Intent intent = new Intent("com.android.scanner.ENABLED");
        intent.putExtra("enabled", flag);
        sendBroadcast(intent);
    }

    /**
     * 扫描声音开关
     *
     * @param flag 是否开启标志
     */
    private void soundPlay(boolean flag) {
        Intent intent = new Intent("com.android.scanner.service_settings");
        intent.putExtra("sound_play", flag);
        sendBroadcast(intent);
    }

    /**
     * 震动开关
     *
     * @param flag 是否开启标志
     */
    private void scanViberate(boolean flag) {
        Intent intent = new Intent("com.android.scanner.service_settings");
        intent.putExtra("viberate", flag);
        sendBroadcast(intent);
    }

    /**
     * 连续扫描开关
     */
    private void scanContinue(boolean flag) {
        Intent intent = new Intent("com.android.scanner.service_settings");
        intent.putExtra("scan_continue", flag);
        sendBroadcast(intent);
    }

    /**
     * 扫描时间间隔
     *
     * @param time 时间间隔
     */
    private void scanInterval(Long time) {
        Intent intent = new Intent("com.android.scanner.service_settings");
        intent.putExtra("interval", 3000);
        sendBroadcast(intent);
    }
}
